package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.AdminGoodsCreateBo;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.AdminGoodsDetailVo;
import com.cskaoyan.bean.vo.goods.brand.BrandListBean;
import com.cskaoyan.bean.vo.goods.brand.CategoryListBean;
import com.cskaoyan.bean.vo.goods.brand.ChildrenBean;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: Tao
 * @time: 2022/12/28 23:08
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;
    @Autowired
    MarketGoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;

    /**
     * 获取商品列表
     * @param info
     * @param goodsId
     * @param goodsSn
     * @param name
     * @return
     */
    @Override
    public CommonData<MarketGoods> getList(BasePageInfo info, Integer goodsId, String goodsSn, String name) {
        //先判断一下是不是优惠券管理模块发过的请求，如果是优惠券管理模块发过来的请求limit是0，则应该查询所有的商品
        if (info.getLimit() != 0) {
            //开启分页
            PageHelper.startPage(info.getPage(), info.getLimit());
            //实例化对象
            MarketGoodsExample example = new MarketGoodsExample();
            //先排序
            example.setOrderByClause(info.getSort() + " " + info.getOrder());
            //增加条件查询
            MarketGoodsExample.Criteria criteria = example.createCriteria();
            // 查询逻辑存在,表中deleted字段值为1是删除状态
            criteria.andDeletedEqualTo(false);
            //对数据进行判空，如果数据是null则此sql语句不执行
            if (goodsId != null) {
                criteria.andIdEqualTo(goodsId);
            }
            if (!StringUtil.isEmpty(goodsSn)) {
                criteria.andGoodsSnEqualTo(goodsSn);
            }
            if (!StringUtil.isEmpty(name)) {
                criteria.andNameLike("%" + name + "%");
            }
            //获取商品表
            List<MarketGoods> list = goodsMapper.selectByExample(example);
            //封装
            PageInfo<MarketGoods> pageInfo = new PageInfo<>(list);
            //进一步封装
            return CommonData.data(pageInfo);
        } else {
            //是优惠券管理木块发过来的请求应该查询所有的商品
            //实例化对象
            MarketGoodsExample example = new MarketGoodsExample();
            //增加条件查询
            MarketGoodsExample.Criteria criteria = example.createCriteria();
            // 查询逻辑存在,表中deleted字段值为1是删除状态
            criteria.andDeletedEqualTo(false);
            //获取商品表
            List<MarketGoods> list = goodsMapper.selectByExample(example);
            //封装
            PageInfo<MarketGoods> pageInfo = new PageInfo<>(list);
            //以下三条公网上显示的全是0，在这里设置下 limit page pages
            pageInfo.setPageSize(0);
            pageInfo.setPageNum(0);
            pageInfo.setPages(0);
            //进一步封装
            return CommonData.data(pageInfo);
        }
    }

    /**
     * 查找所有的品牌
     *
     * @return 品牌表
     */
    @Override
    public List<BrandListBean> getBrand() {
        MarketBrandExample example = new MarketBrandExample();
        List<MarketBrand> marketBrands = brandMapper.selectByExample(example);
        //封装
        ArrayList<BrandListBean> brandListBeans = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            BrandListBean brandBean = new BrandListBean();
            brandBean.setValue(marketBrand.getId());
            brandBean.setLabel(marketBrand.getName());
            brandListBeans.add(brandBean);
        }
        return brandListBeans;

    }

    /**
     * 查找所有商品的种类
     *
     * @return
     */
    @Override
    public List<CategoryListBean> getcategory() {
        //先找出所有的父种类
        MarketCategoryExample example = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andPidEqualTo(0);
        //marketCategories中有所有父种类的所有信息
        List<MarketCategory> marketCategories = categoryMapper.selectByExample(example);

        //封装,此时marketCategories中都是父种类，即pid= 0
        ArrayList<CategoryListBean> categoryListBean = new ArrayList<>();
        for (MarketCategory marketCategory : marketCategories) {
            CategoryListBean categoryBean = new CategoryListBean();
            Integer id = marketCategory.getId();
            categoryBean.setValue(id);
            categoryBean.setLabel(marketCategory.getName());
            //找父种类对应的子种类
            MarketCategoryExample example2 = new MarketCategoryExample();
            MarketCategoryExample.Criteria criteria2 = example2.createCriteria();
            criteria2.andPidEqualTo(id);
            //此时找到了此父类对应的所有子类（全部信息）放在了 marketSonCategories集合中，还需要进一步封装
            List<MarketCategory> marketSonCategories = categoryMapper.selectByExample(example2);
            //创建封装此子种类（id和name）的集合
            ArrayList<ChildrenBean> childrenBeans = new ArrayList<>();
            for (MarketCategory marketSonCategory : marketSonCategories) {
                ChildrenBean childrenBean = new ChildrenBean();
                childrenBean.setValue(marketSonCategory.getId());
                childrenBean.setLabel(marketSonCategory.getName());
                childrenBeans.add(childrenBean);
            }
            //此时已经找到此父类的所有子种类（id和name）的集合
            categoryBean.setChildren(childrenBeans);
            //将此父种类加入到集合中
            categoryListBean.add(categoryBean);

        }

        //返回封装所有种类（包括子种类）的集合
        return categoryListBean;
    }

    /**
     * 删除商品的方法
     *
     * @param marketGoods
     */
    @Override
    public void deleteGoods(MarketGoods marketGoods) {
        // 获得 要删除的商品的id
        Integer id = marketGoods.getId();
        // 获得 要删除的商品的逻辑删除标志
        Boolean deleted = marketGoods.getDeleted();
        // 通过id 更新 删除标记
        MarketGoods goodsDelete = new MarketGoods();
        goodsDelete.setId(id);
        // 删除标记取反
        goodsDelete.setDeleted(!deleted);
        goodsMapper.updateByPrimaryKeySelective(goodsDelete);
    }

    /**
     * 查询商品的detail
     *
     * @param id
     * @return 商品的detail
     */
    @Override
    public AdminGoodsDetailVo getDetail(Integer id) {
        //id是商品的id
        AdminGoodsDetailVo adminGoodsDetail = new AdminGoodsDetailVo();
        //先封装商品
        //实例化对象
        MarketGoodsExample example = new MarketGoodsExample();
        //增加条件查询
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        //获取商品表
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(example);
        MarketGoods goods = marketGoods.get(0);
        //封装商品
        adminGoodsDetail.setGoods(goods);

        //再封装商品的种类
        //这个是子种类的id
        Integer categoryIdSon = goods.getCategoryId();
        //增加条件判断：如果在添加商品种类时没有选择种类，商品的种类（存放的子种类）id为0，此时detail里应该不显示种类，以下不执行
        if (categoryIdSon != 0) {
            //根据子种类的id查勋父种类的id
            //实例化对象
            MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
            //增加条件查询
            MarketCategoryExample.Criteria criteria1 = marketCategoryExample.createCriteria();
            criteria1.andIdEqualTo(categoryIdSon);
            List<MarketCategory> marketCategories = categoryMapper.selectByExample(marketCategoryExample);
            MarketCategory marketCategory = marketCategories.get(0);
            //得到父种类的id
            Integer pid = marketCategory.getPid();
            //子种类和父种类封装
            ArrayList<Integer> categoryIds = new ArrayList<>();
            //父种类封装
            categoryIds.add(pid);
            //子种类封装
            categoryIds.add(categoryIdSon);
            //最终注入VO
            adminGoodsDetail.setCategoryIds(categoryIds);
        }

        //再封装商品的属性
        //实例化对象
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        //增加条件查询
        MarketGoodsAttributeExample.Criteria criteria2 = marketGoodsAttributeExample.createCriteria();
        criteria2.andGoodsIdEqualTo(id);
        //获取商品的所有属性
        List<MarketGoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        //封装
        adminGoodsDetail.setAttributes(goodsAttributes);


        //再封装products规格
        //实例化对象
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        //增加条件查询
        MarketGoodsProductExample.Criteria criteria3 = marketGoodsProductExample.createCriteria();
        criteria3.andGoodsIdEqualTo(id);
        //获取商品的所有products 规格
        List<MarketGoodsProduct> marketGoodsProducts = productMapper.selectByExample(marketGoodsProductExample);
        //封装
        adminGoodsDetail.setProducts(marketGoodsProducts);


        //最后封装specifications 规格
        //实例化对象
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        //增加条件查询
        MarketGoodsSpecificationExample.Criteria criteria4 = marketGoodsSpecificationExample.createCriteria();
        criteria4.andGoodsIdEqualTo(id);
        //获取商品的所有specifications  规格
        List<MarketGoodsSpecification> marketGoodsSpecifications = specificationMapper.selectByExample(marketGoodsSpecificationExample);
        //封装
        adminGoodsDetail.setSpecifications(marketGoodsSpecifications);

        //最终返回detail
        return adminGoodsDetail;
    }


    /**
     * 修改商品
     *
     * @param goods
     * @param attributes
     * @param products
     * @param specifications
     */
    @Override
    public void updateGoods(MarketGoods goods, List<MarketGoodsAttribute> attributes,
                            List<MarketGoodsProduct> products, List<MarketGoodsSpecification> specifications) {
        //修改商品
        //修改商品的修改时间
        goods.setUpdateTime(new Date());
        //修改商品的当前价格
        MarketGoodsProduct goodsProduct = products.get(0);
        BigDecimal price = goodsProduct.getPrice();
        goods.setRetailPrice(price);
        //修改商品
        goodsMapper.updateByPrimaryKeySelective(goods);


        //修改商品的属性
        for (MarketGoodsAttribute attribute : attributes) {
            //如果属性的id存在表示执行修改
            if (attribute.getId() != null) {
                attribute.setUpdateTime(new Date());
                goodsAttributeMapper.updateByPrimaryKeySelective(attribute);
            } else {
                //如果属性的id不存在表示执行插入
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                //表示不删除
                attribute.setDeleted(false);
                //获取商品的id
                attribute.setGoodsId(goods.getId());
                goodsAttributeMapper.insertSelective(attribute);
            }

        }
        //修改商品规格products
        for (MarketGoodsProduct product : products) {
            productMapper.updateByPrimaryKeySelective(product);
        }

        //修改商品规格specifications
        for (MarketGoodsSpecification specification : specifications) {
            specificationMapper.updateByPrimaryKeySelective(specification);
        }

    }

    /**
     * 增加商品
     *
     * @param goodsCreateBO
     */
    @Override
    public int createGoods(AdminGoodsCreateBo goodsCreateBO) {
        //注：返回值为0代表成功，返回值为1代表参数异常
        //先取出商品 属性 规格
        MarketGoods goods = goodsCreateBO.getGoods();
        List<MarketGoodsAttribute> attributes = goodsCreateBO.getAttributes();
        List<MarketGoodsProduct> products = goodsCreateBO.getProducts();
        List<MarketGoodsSpecification> specifications = goodsCreateBO.getSpecifications();

        //再创建商品
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        //取出商品的当前价格
        MarketGoodsProduct marketGoodsProduct = products.get(0);
        BigDecimal price = marketGoodsProduct.getPrice();
        String s = String.valueOf(price);
        Double prices = null;
        try {
            //这个仅仅作为验证是不是数字，以及是不是正数
            prices = Double.valueOf(s);
            if (prices <= 0) {
                return 1;
            }
            //给所插入商品现在的价格赋值
            goods.setRetailPrice(price);
            //插入商品
            goodsMapper.insertSelective(goods);

        } catch (Exception e) {
            //插入失败
            return 1;
        }


        //再创建商品属性信息
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setAddTime(new Date());
            attribute.setUpdateTime(new Date());
            //表示不删除
            attribute.setDeleted(false);
            //获取商品的id
            attribute.setGoodsId(goods.getId());
            goodsAttributeMapper.insertSelective(attribute);
        }

        //再创建商品的规格信息product
        for (MarketGoodsProduct product : products) {
            product.setId(null);
            //获取商品的id
            product.setGoodsId(goods.getId());
            product.setAddTime(new Date());
            product.setUpdateTime(new Date());
            product.setDeleted(false);
            //插入
            productMapper.insertSelective(product);
        }

        //最后再创建商品的规格信息specification
        for (MarketGoodsSpecification specification : specifications) {
            //获取商品的id
            specification.setGoodsId(goods.getId());
            specification.setAddTime(new Date());
            specification.setUpdateTime(new Date());
            specification.setDeleted(false);
            //插入
            specificationMapper.insertSelective(specification);
        }
        //插入成功
        return 0;
    }
}
